(index):128 Uncaught TypeError: MobileNumberVal.test is not a function

Created at 12-Jul-2023 , By samar

I am getting an error (index):128 Uncaught TypeError: MobileNumberVal.test is not a function while using !MobileNumberVal.test(regexMobile) in my function while validating the mobile number on form submit.

Here is my code. Give me a solution for the error.

HTML Input element

<input type="text" class="form-control" name="mobile" id="mobileNumber">

Javascript code

var mobileNumberElem = $('#mobileNumber');
var MobileNumberVal  = mobileNumberElem.val();
var regexMobile = /^\d{10}$/;

if(!MobileNumberVal.test(regexMobile)){
    showErrorMsg(mobileNumberElem, 'Please provide accurate mobile number !');
    isValid = false;
}
  • Replace !MobileNumberVal.test(regexMobile) with !regexMobile.test(MobileNumberVal)

    You have to just replace the code !MobileNumberVal.test(regexMobile) with !regexMobile.test(MobileNumberVal) in your script. Your code will look like below.

    var mobileNumberElem = $('#mobileNumber');
    var MobileNumberVal  = mobileNumberElem.val();
    var regexMobile = /^\d{10}$/;
    
    if(!MobileNumberVal.test(regexMobile)){
        showErrorMsg(mobileNumberElem, 'Please provide accurate mobile number !');
        isValid = false;
    }
    

Back to code snippet queries related jquery

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.