2

I have a form validator by AntonLapshin where I'm trying to validate a non-empty input field which can only take alphabets, space, - and '. The alphabets can be a-z, A-Z and europian letters æÆøØåÅöÖéÉèÈüÜ, etc. See this for more details.

Here is what I am doing:

method  : function(input) {
    return input.value !== ''
        && input.value === /^[a-zA-Z'\- \u00c0-\u017e]+$/
}

Here, it should match: Åløæ-Bond Mc'Cool

But fail: 123-Bond Mc'C@o!

When I run ^[a-zA-Z'\- \u00c0-\u017e]+$ in regex tester, It works absolutely fine, but in my script, it is not validating and throws an invalid input error.

What am I doing wrong?

3
  • Would be helpful to have the error from your script Commented Jul 3, 2018 at 5:30
  • What error is coming from your script? Commented Jul 3, 2018 at 5:30
  • There's no syntax error in my script. It's just the regex pattern not working. Commented Jul 3, 2018 at 5:44

3 Answers 3

2

I prefer to use RegExp. You also need to do return pattern.test(input)

This will work :)

var test1 = "Åløæ-Bond Mc'Cool";
var test2 = "123-Bond Mc'C@o!";

var pattern = new RegExp(/^[a-zA-Z'\- \u00c0-\u017e]+$/);

function regextest(input) {
    return input !== '' && pattern.test(input)
}

console.log(regextest(test1))
console.log(regextest(test2))

Sign up to request clarification or add additional context in comments.

2 Comments

Using RegExp is not necessary, but pattern.test is ;)
Really? @Zim Wow, I never realized that :) Learn something new every day ;) updated
1

modify your function to test with regex

var pattern = /^[a-zA-Z'\- \u00c0-\u017e]+$/

var method = function(input) {
  return input !== '' &&
    pattern.test(input)
}

//your sample strings
console.log(method("Åløæ-Bond Mc'Cool"))
console.log(method("123 - Bond Mc 'C@o!"))

1 Comment

Don't know how there are 2 upvotes on this answer.. it doesn't work for me @CodeMonk
0

I figured out a simpler solution for my question:

method  : function(input) {
    return input.value !== '' && /^[a-zA-Z'\- \u00c0-\u017e]+$/.test(input.value)
}

The problem was, after the && operator, I was checking for the input value (that’s wrong in regex check) instead of Boolean value.

This solution works perfectly and creates no confusion.

1 Comment

You’re right. I’m only referring to the readability referring to my own question

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.