0

I am trying to write a small javascript validation to allow english and french alphabets. This is how I have the regex...but its returning false. I was looking at this

Check whether a string matches a regex

var string = "évaÀ";
var re = new RegExp("/[^a-zA-Z àâäèéêëîïôœùûüÿçÀÂÄÈÉÊËÎÏÔŒÙÛÜŸÇ]/");
if (re.test(string)) {
  console.log("true");
} else {
  console.log("false");
}

What am I doing wrong? Here is a fiddle

https://jsfiddle.net/sghoush1/e36jquLf/1/

Community
  • 1
  • 1
soum
  • 1,131
  • 3
  • 20
  • 47

2 Answers2

2

You want the ^ to be outside the brackets, and make sure you have any amount of these charecters inbetween the start ^ and the end $ of the string: (You also need to remove the "...", and you don't realy need the new RegEx)

var string = "évaÀ";
var re = /^[a-zA-Z àâäèéêëîïôœùûüÿçÀÂÄÈÉÊËÎÏÔŒÙÛÜŸÇ]*$/
if (re.test(string)) {
  console.log("true");
} else {
  console.log("false");
}

// For the Demo-Input
function test(el) {
  if (/^[a-zA-Z àâäèéêëîïôœùûüÿçÀÂÄÈÉÊËÎÏÔŒÙÛÜŸÇ]*$/.test(el.value)) {
    el.style.background = "green"
  } else {
    el.style.background = "red"
  }
}
<form>
  <input type="text" oninput="test(this)" placeholder="test any string here" />
  <input type="submit">
</form>
CoderPi
  • 12,985
  • 4
  • 34
  • 62
0

Can you try this:

var string = "évaÀ"
if(string.match(/^[a-zA-Z àâäèéêëîïôœùûüÿçÀÂÄÈÉÊËÎÏÔŒÙÛÜŸÇ]+$/)){
  console.log("true");
} else {
  console.log("false");
}
Raman
  • 1,221
  • 13
  • 20
  • 1
    Can you please let me know why you have marked the answer negative, according to me it at least doesn't fail to give the expected output. – Raman Dec 30 '15 at 14:07