I've tried a lot of things but I can't seem to make it work
Problem is whatever I type is considered false, even when I try valid email adress (such as ok#gmail.com)
Here's my code
function validateEmail(email) {
var re = /[^\s#]+#[^\s#]+\.[^\s#]+/;
return re.test(email);
}
var email = $('input[name = pEmail]').val();
$('#nPopupSubmit').click(function () {
if (!validateEmail(email)) {
$('label[id = pEmailError]').show();
$('input[name = pEmail]').focus();
return false;
} else {
whatever
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<form id="popup1" method="post">
<fieldset>
<input id="pEmail" type="text" placeholder="E-mail" value="E-mail" onclick="this.value=''" class="popup_input" name="pEmail" type="text" />
<label id="pEmailError" style="color:#FF0000; display:none;">Error</label>
<button type="submit" id="nPopupSubmit" name="nPopupSubmit">Go !</button>
</fieldset>
</form>
Do any of you have a clue on what's going on ?
Thank you !
Your function doesn't contain error, perhaps your jQuery? Your email variable should be defined after the click, otherwise, email's value would always = "Email" (the default value)
$('#nPopupSubmit').click(function () {
var email = $('#pEmail').val(); //<-- This is where you should put this
if (!validateEmail(email)) {
$('#pEmailError').show();
$('#pEmail').focus();
return false;
} else {
//whatever
}
});
Also, you can simplify your code by using the ids you have already given your elements :)
function validateEmail(email) {
var re = /[^\s#]+#[^\s#]+\.[^\s#]+/;
return re.test(email);
}
$('#nPopupSubmit').click(function () {
var email = $('#pEmail').val();
if (validateEmail(email) !== true) {
$('#pEmailError').show();
$('#pEmail').focus();
return false;
} else {
//whatever
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="popup1" method="post">
<fieldset>
<input id="pEmail" type="text" placeholder="E-mail" value="E-mail" onclick="this.value=''" class="popup_input" name="pEmail" type="text" />
<label id="pEmailError" style="color:#FF0000; display:none;">Error</label>
<button type="submit" id="nPopupSubmit" name="nPopupSubmit">Go !</button>
</fieldset>
</form>
Your current regex won't validate how you want.
You can try this:
function validateEmail(email) {
var re = new RegExp("^[^\\s#]+#[^\\s#]+?\\.[^\\s#]+$", "m");
console.log(email.match(re));
if(email.match(re))
{
return true;
}
else
{
return false;
}
}
window.alert(validateEmail("a#b.c"));
window.alert(validateEmail("a #b.c"));
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<script>
function validateEmail(email) {
var re = new RegExp("^[^\\s#]+#[^\\s#]+?\\.[^\\s#]+$", "m");
console.log(email.match(re));
if(email.match(re))
{
return true;
}
else
{
return false;
}
}
console.log(validateEmail("a#b.c"));
</script>
</body>
</html>
Hope that helps. If you have any questions on specifics just let me know...
Related
I have below code that is working fine, but I want to validate textbox TBMonday to force users to enter in the specified pattern. How can I do this with Javascript (Please I don't want to use input type='time')
<input type="text" id="TBMonday" size="7" placeholder="hh:mm-hh:mm" pattern="(2[0-4]|1[0-9]|[1-
9])\:(5[0-9]|4[0-9]|3[0-9]|2[0-9]|1[0-9]|[0-9])-(2[0-4]|1[0-9]|[1-9])\:(5[0-9]|4[0-9]|3[0-
9]|2[0-9]|1[0-9]|[0-9])" onKeyUp="TBMondayEl();">
<input type="text" id="TBMonday2" size="7">
<script>
function TBMondayEl()
{
document.getElementById('TBMonday2').value = document.getElementById('TBMonday').value;
}
</script>
Here is how I finally write my code and it work for me.
<input type="text" id="TBMonday" size="7" placeholder="hh:mm-hh:mm" required
onblur="validateMon();" onKeyUp="TBMondayEl();">
<input type="text" id="TBMonday2" size="7">
<script>
function validateMon(){
var phoneNumber = document.getElementById('TBMonday').value;
var phoneRGEX = /^(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]-(0[0-9]|1[0-9]|2[0-3]):[0-5]
[0-9]$/;
var phoneResult = phoneRGEX.test(phoneNumber);
if(phoneResult == false)
{
document.getElementById('TBMonday').value = '';
document.getElementById('TBMonday2').value = '';
alert('Please enter TimeBelt in "HH:MM-HH:MM" format');
return false;
}
return true;
}
<script>
function TBMondayEl()
{
document.getElementById('TBMonday2').value
document.getElementById('TBMonday').value;
}
</script>
I am trying to validate a form field using Regex. The field should contain 5 numbers (ie 12345 = valid, 1234a = invalid, 123456 = invalid), that is it. no more, no less. The problem is with different regex formats, the .test() method either always returns true, or always returns false. It never works for correct values and fails for incorrect values. All regex testers test the regex successfully for JavaScript but when I add it to my page (WordPress), I get these issues. I read up about the /g field should be removed and tried all that. still no luck.
HTML:
<form name="newform" action="Create.php" onsubmit="return validateForm()" method="POST" >
Code <br/><br/><input id="code" class="form-control" type="text" value="" name="code" onkeypress="CodeStyleRefresh()" />
<button type="submit" id="submit" name="submit">Create</button>
</form>
JavaScript:
<script type="text/javascript">
function validateForm(){
var CodePattern = new RegExp(/\b\d{5}\b/);
if(CodePattern.test(document.forms["newform"]["code"].value) == true)
{
return true;
}
else
{
return false;
}
}
function CodeStyleRefresh(){
document.getElementById("code").setAttribute("style", "background-color: #ffffff;");
}
</script>
Some other ways I have tried to specify the expression:
var CodePattern = new RegExp(/\b\d{5}\b/);
var CodePattern = new RegExp('/\b\d{5}\b/');
var CodePattern = /\b\d{5}\b/;
var CodePattern = '/\b\d{5}\b/';
var CodePattern = \b\d{5}\b;
var CodePattern = '\b\d{5}\b';
This is my first time ever touching regex and I am fairly new to the JavaScript family as well. Not having such a good time.
UPDATE:
I have gone back to basics. My JavaScript now looks as follows based on a few suggestions:
function validateForm(event)
{
console.log("Im running the script!");
console.log(event.target.querySelector("[name=code]").value);
var CodePattern = new RegExp(/\b\d{5}\b/);
var codeVal = event.target.querySelector("[name=code]").value;
if(CodePattern.test(codeVal) == true)
{
alert("Expression Passed!");
}
else
{
alert("Expression Failed!");
return false;
}
}
My HTML is now:
<form name="newform" onsubmit="return validateForm(event)" method="POST">
Code
<input id="code" class="form-control" type="text" value="" name="code" />
<button type="submit" id="submit" name="submit">Create</button>
</form>
Still this expression is only hitting the failed state and alerts expression failed.
If it helps, I am adding the JavaScript to a WordPress page, the form is normal html on the same page. I have tried adding the JavaScript to both the header and the footer but this does not change anything. I'm starting to think I should just check if the length of the field = 5 and if I can then cast it to an int instead of using RegEx at all!
Your regex is fine. If you are only getting the error when you upload your code to your wordpress site, I'd be tempted to say that your problem is your context, perhaps you have more than one form with the same name?
Try a context aware piece of code, update your html to:
<form name="newform" onsubmit="return validateForm(event)" method="POST">
Code
<input id="code" class="form-control" type="text" value="" name="code" onkeypress="CodeStyleRefresh()" />
<button type="submit" id="submit" name="submit">Create</button>
</form>
And your javascript:
function validateForm(event){
var myRegex = new RegExp(/\b\d{5}\b/);
//event.target holds the node element that triggered the function in our case, the Form itself
var myValue = event.target.querySelector("[name=code]").value; //here we find the input with the name=code inside the form that triggered the event
return myRegex.test(myValue) //return true if it passed, false if not
}
Since I cannot insert this much code in comments, I am posting an answer here to show how it all works.
function validateForm(frm, evt)
{
var codeVal = frm.code.value;
var CodePattern = /\b\d{5}\b/;
// comment below line after testing
evt.preventDefault();
if(CodePattern.test(codeVal) == true)
{
console.log("Expression Passed!");
return true;
}
else
{
console.log("Expression Failed!");
return false;
}
}
<form name="newform" onsubmit="return validateForm(this, event)" method="POST">
Code <br/><br/>
<input id="code" type="text" value="abc 12345 foo bar" name="code" />
<input type="submit" id="submit" name="submit" value="Create" />
</form>
Thank you for all the suggestions. I have learnt a few things by looking at them all and I have made a few changes.
I could not however get the regex to work properly in wordpress. I was forced to create a longwinded, dirtier solution to this. I will continue to look at possible solutions and test on other wordpress sites, but for now, this is the code I am using to validate the field:
function validateForm(frm, evt)
{
var codeVal = frm.code.value;
console.log("Code Value: " + String(codeVal));
// comment below line after testing
evt.preventDefault();
var lenPass = false;
var strlen = codeVal.length;
if(strlen == 5)
{
lenPass = true;
}
if(lenPass)
{
var c1 = Number.isNaN(Number(codeVal.charAt(0)));
var c2 = Number.isNaN(Number(codeVal.charAt(1)));
var c3 = Number.isNaN(Number(codeVal.charAt(2)));
var c4 = Number.isNaN(Number(codeVal.charAt(3)));
var c5 = Number.isNaN(Number(codeVal.charAt(4)));
console.log(c1);
console.log(c2);
console.log(c3);
console.log(c4);
console.log(c5);
var pass = true;
if(c1)
{
pass = false;
}
if(c2)
{
pass = false;
}
if(c3)
{
pass = false;
}
if(c4)
{
pass = false;
}
if(c5)
{
pass = false;
}
if(pass)
{
alert("Expression Stage 2 Passed!");
return true;
}
else
{
alert("Expression Stage 2 Failed!");
return false;
}
}
else
{
alert("Expression Stage 1 Failed!");
return false;
}
}
<html>
<head>
</head>
<body>
<form name="newform" onsubmit="return validateForm(this, event)" method="POST">
Code <br/><br/>
<input id="code" type="text" value="" name="code" />
<input type="submit" id="submit" name="submit" value="Create" />
</form>
</body>
</html>
I have an input type =text in html and i have this js code in js file to show error message
var $form = $("#myid"),
$errorMsg = $("<span id='myerrormessagespan' class='error' style='color:red;'>*</span>");
var toReturn = 0;
$("input", $form).each(function () {
if ($(this).val() == "") {
if (!$(this).data("error")) {
$(this).data("error", $errorMsg.clone().insertAfter($(this)));
}
toReturn = 1;
}
else {
if ($(this).data("error")) {
$(this).data("error").remove();
$(this).removeData("error");
}
}
});
I am trying to convert this code to make range validator on input type=text field .dispalying only 5 digits in the textbox, but i couldn't achieve . Is there any easy way to do this ?
Thanks
Consider using the jQuery validation plugin instead, especially the rangelength method for your case. However, if you want to stick to the original code without using any library then I suggest you try the code below for example:
HTML:
<form id="myid" name="myid" method="post" action="/">name :
<input type="text" name="name" id="name" />age :
<input type="text" name="age" id="age" />
<input type="submit" id="submit" name="submit" value="Save" />
</form>
jQuery:
var $form = $("#myid"),
$errorMsg = $("<span id='myerrormessagespan' class='error' style='color:red;'>*</span>");
$("#submit").on("click", function () {
var toReturn = true;
$("input", $form).each(function () {
var value = $(this).val();
if((!$.trim(this.value).length) || (value.length > 5)) {
if (!$(this).data("error")) {
$(this).data("error", $errorMsg.clone().insertAfter($(this)));
}
toReturn = false;
}
else {
if ($(this).data("error")) {
$(this).data("error").remove();
$(this).removeData("error");
}
}
});
return toReturn;
});
Working JSFiddle Demo
I want that Name field should contain text only.
<html>
<head></head>
<body>
<form name="form1">
Name <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>
Can anyone tell me how can I do so using either HTML or Javascript.
Use this regex in your Javascript: /^[a-z]+$/i
WORKING DEMO
Javascript:
var submit = document.getElementById("submit");
submit.addEventListener("click", checkInput, false);
function checkInput(e){
e.preventDefault();
var pattern = /^[a-z]+$/i;
alert(pattern.test(document.getElementById('text').value));
}
You can test whether there's "anything left" after removing alpha characters.
<html>
<body>
<form name="form1" onsubmit="return checkform();">
Name<input type="text" name="fname" id="fname">
<input type="submit" value="Submit">
</form>
<script>
function checkform(){
var fname=document.getElementById('fname').value;
if (fname.replace(/\w/g,'')!=''||fname==''){
alert('invalid firstname!');
return false;
}
return true;
}
</script>
</body>
</html>
try this:
<script type="text/javascript">
function validate(){
var allowedChars="abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var n=form1.fname.value;
for(var i=0;i<n.length;i++){
if(allowedChars.indexOf(n.charAt(i))==-1){
return false; // contains other char
}
}
return true; //valid name
}
Try regular expressions like
var match_text = /[a-zA-Z]/;
try this var regx = /^[A-Za-z][-a-zA-Z ]+$/;
function validate_form();
{
var regx = /^[A-Za-z][-a-zA-Z ]+$/;
var fname = document.getElementById('fname').value;
if(fname=="")
{
alert("Name is Blank");
return false;
}
else if(!regx.test(fname))
{
alert("name must contains character only");
return false;
}
else
{
return true;
}
}
Pattern checking of the textbox must be done with Javascript or Jquery like in other answers BUT if you want to use HTML5, you can directly write :
<input type="text" name="fname" id="fname" pattern="[A-Za-z]+" />
(See 'pattern' attribute in HTML5 if you're interested).
You can call this function to validate input field containing only text--
function validate()
{
str = document.form1.fname.value;
var patt = new RegExp("^[a-zA-Z ]*$");
var res = patt.test(str);
if(!res)
{
alert("do not match!");
return false;
}
}
So, I have this code
<script>
function validate(f) {
var ok = true;
if (f.id.value === '' || f.id.value === null) {
ok = false;
}
return ok;
}
function validate2(f) {
var ok = true;
if (f.name.value === '' || f.name.value === null) {
ok = false;
}
return ok;
}
</script>
<form action="#" method="post">
<input type="text" name="id"/>
<input type="text" name="name"/>
<input type="submit" name="send_id" value="Send ID"/>
<input type="submit" name="send_name" value="Send Name"/>
</form>
How can I do it to validate the form depending on which submit is used?
I want to execute validate(); if the Send Id button is clicked and validate2() if we use the other one.
You can do this:
<form id="myForm" action="#" method="post">
<input type="text" name="id"/>
<input type="text" name="name"/>
<input type="submit" name="send_id" value="Send ID" onclick="return validate();" />
<input type="submit" name="send_name" value="Send Name" onclick="return validate2();" />
</form>
This way when your functions return false (meaning the form is not valid) the submit is interrupted.
And get your f parameter manually.
function getForm() {
return document.getElementById("myForm");
}
function validate() {
var f = getForm();
var ok = true;
if (f.id.value === '' || f.id.value === null) {
ok = false;
}
return ok;
}
function validate2() {
var f = getForm();
var ok = true;
if (f.name.value === '' || f.name.value === null) {
ok = false;
}
return ok;
}
You have to give an id to your form as show above.
Have another function as checkValidate() or something as you like and check it on click of both the buttons
<script>
function checkValidate(buttonName) {
if(buttonName == 'send_id'){
return validate();
}else{
return validate2();
}
}
function validate() {
var ok = true;
if (f.id.value === '' || f.id.value === null) {
ok = false;
}
return ok;
}
function validate2() {
var ok = true;
if (f.name.value === '' || f.name.value === null) {
ok = false;
}
return ok;
}
</script>
<form action="#" method="post">
<input type="text" name="id"/>
<input type="text" name="name"/>
<input type="submit" name="send_id" value="Send ID" onclick="return checkValidate(this.name)"/>
<input type="submit" name="send_name" value="Send Name" onclick="return checkValidate(this.name)"/>
</form>
I hope it helps...
Not tested.. but something like that...
$( "input[name='send_id']" ).click(function(event) {
event.preventDefault()
validate();
$("form").submit();
});
$( "input[name='send_name']" ).click(function(event) {
event.preventDefault()
validate2();
$("form").submit();
});