简体   繁体   中英

Javascript function using regex

I have created a function using reg-ex to validate a field in JavaScript. My function is

//FIRST NAME VALIDATION
var strFilter = /^[A-Za-z]*$/;
var fname = document.getElementById('fname');
fname = fname.value.replace(/^\s+|\s+$/g,'');

if ( ( !strFilter.test(fname.value) ) || fname == '') { 
    alert("Please enter a valid first name\r\n (only characters)");
    document.getElementById('fname').style.background = '#DFE32D';
    document.getElementById('fname').focus();
    document.getElementById('fname').value = '';
    return false;
}

Issue with the function is, it is taking stackoverflow234232 also as true. I want to constrain it for character only.

I think your problem is on this line -

if ((!strFilter.test(fname.value)) || fname == '') { 

it should be -

if ((!strFilter.test(fname) ) || fname == '') { 

fname is a string variable by the time you get to the if statement, so fname.value is returning undefined and the call to test is not working.

Try this instead

<!--   FIRST NAME VALIDATION   -->
var strFilter = /^[A-Za-z]*$/;
var fname = $('#fname');
fname.val(fname.val().replace(/^\s+|\s+$/g,''));


if ( ( !strFilter.test(fname.val()) ) || fname == '') {
    alert("Please enter a valid first name\r\n (only characters)");
    $('#fname').css('background-color','#DFE32D');
    $('#fname').focus();
    $('#fname').val('');
    return false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM