0

I am having a problem with regular expression in javascript. What i am trying to do is a form register in which i must validate the first name so i decided to go with javascript validation (can you please tell me if going with js is the better option or going with ajax php reg validation?). So I wrote my code by checking some tutorials and reading from google but i am still having a problem. It is not working ! It runs on blur event using jquery so I need your help please to do this. The pattern i am trying to check is for special characters in the user input /[\'^£$%&*()}{@#~?><>,|=_+]+$/g;

here is my script:

                $(document).on('blur','.first_name_input', function() {

                    var firstNameInput = $(".first_name_input").val();

                    if (firstNameInput !== '') {

                        //var exp = /[a-zA-Z0-9-]+$/g;
                        var exp = /[\'^£$%&*()}{@#~?><>,|=_+]+$/g;
                        //if (firstNameInput.test(/^[\'^£$%&*()}{@#~?><>,|=_+-]+$/)) {
                        //if (firstNameInput.match(/[a-zA-Z0-9]*/g)) {
                        if (firstNameInput.match(exp)) {
                            var firstnameValidity = "<div class='name_not_valid_div'>&times; Not allowed characters present!</div>";
                            $('body').prepend(firstnameValidity);
                            $(".name_not_valid_div").hide().fadeIn('slow');

                            if (!errorArray.includes("firstName")){
                                errorArray.push("firstName");
                            }
                        } else {
                            $(".name_not_valid_div").hide();

                            if (errorArray.includes("firstName")){
                                for(var i = errorArray.length - 1; i >= 0; i--) {
                                    if(errorArray[i] === "firstName") {
                                       errorArray.splice(i, 1);
                                    }
                                }
                            }
                        }
                    }

                });

and my html code is :

<tr>
                <td class="label">First Name: </td>
                <td class="input"><input type="text" name="first_name" class="input_bar first_name_input" size="30" Placeholder="First Name" /><br/></td>
            </tr>

1 Answer 1

2

1st: use .trim() to avoid left/right whitespaces or even the spaces without any characters $(".first_name_input").val().trim();

2nd: for validation

// if the string has special characters
function string_has_spec_char(str){
    var reg = /[~`!#@$%\^&*+=\-\[\]\\';,_./{}\(\)\|\\":<>\?]/g;
    return reg.test(str);
}
// check if string has spaces
function string_has_spaces(str) {
    var reg = /\s/g;
    return reg.test(str);
}

and use it like

if(string_has_spec_char(firstNameInput) === false){
   // the first name doesn't have special characters
}

if(string_has_spaces(firstNameInput) === false){
   // the first name doesn't have spaces
}
Sign up to request clarification or add additional context in comments.

2 Comments

Mohamed thanks a lot !! it worked perfect ! i don't know what was the problem in my regex, i had to make a nested if which means check if first name has special characters if it has give error, if not check for spaces, if it has give error if not give nothing
@firasprogrammer actually I'm not expert on regex .. but what I can say to you is while programming if you find a working regex just keep/save it instead of looking whats wrong in yours unless if you need to be a regex expert.. I recommend to create a validate.js file and put inside it all of your regex/validate functions so you can simply use it on any project later .. Have a greart day :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.