Using javascript for checking forms - javascript

here is my code:
<script>
function check(){
var error = '';
var name = document.forms['form1'].name.value;
var age = document.forms['form1'].age.value;
var checkname = new RegExp("^[a-zA-Z]{3,}$");
var checkage = new RegExp("^[1-9]{1}+[0-9]{1}$");
if (!checkname.test(name)) error+= 'Blad w nameniu\n';
if (!checkage.test(age)) error+= 'Blad w ageu\n';
if (error == '')
return true;
else {
alert(error);
return false;
}
}
</script>
<form name="form1">
<p>Name: <input type="text" name="name"></p>
<p>Age: <input type="text" name="age"></p>
<button type="button" onclick="check()">Send</button>
</form>
I have no idea why the given code simply doesn't work. There is no action at all. I have tried to change <button> to <input type="sumbit"> and <form onSubmit="check()"> but had no luck.
Fiddle

The problem is the regular expression for checkage
var checkage = new RegExp("^[1-9]{1}+[0-9]{1}$");
this needs to be
var checkage = new RegExp("^[1-9]{1}[0-9]{1}$");
And you can use firebug for firefox ( is a free add-on that helps you a lot).
Have a good day.

The problem of your code is the checkage regular expression. Instead of this :
var checkage = new RegExp("^[1-9]{1}+[0-9]{1}$");
You could try :
var checkage = new RegExp("/(^[1-9]?[0-9]{1}$|^100$)/");
But IMHO, regex is not the good way to validate the age. You should just write a simple function which check if the number is in between 0 - 100 range
Hope this helps !

Related

Why is this simple Javascript refactor not working?

A simple question about a form submit in HTML.
Why does this work:
var inputStuff = document.getElementById("inputBox");
var output = document.getElementById("outputBox");
function useMethod(element) {
output.innerText = inputStuff.value;
return false;
}
But this doesn't:
var inputStuff = document.getElementById("inputBox");
var output = document.getElementById("outputBox");
function useMethod(element) {
var out = output.innerText;
var into = inputStuff.value;
out = into;
return false;
}
Here's the HTML:
<h1>Put your input in here</h1>
<form onsubmit="return useMethod(this)" action="">
<input type="text" id="inputBox">
<input type="submit" value="Submit">
</form>
<h2>Output:</h2>
<p id="outputBox">Starter text</p>
Many thanks in advance for any help,
R
out = into; will simply assign the value of into (string) to out (string), whereas output.innerText = inputStuff.value; will invoke an implicit setter that will change the DOM value as well.

Regex always returning either always true or always false regardless of valid test value

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>

how to make innerhtml values as user inputs

I am trying to get the innerElement to a value that is entered by the user but it give me errors. Codes are as above please help
*****Codes*****
var abc= document.getElementById("searchbar").innerHTML = "Singapore Polytechnic"; --instead of Singapore Polytechnic I want it to be some values that was entered by the users.--
document.getElementById("searchbar").contentEditable = "true";
var test = abc;
Try the following:
function changeVal(ele){
document.getElementById("searchbar").innerHTML = ele.value;
}
<p id="searchbar">Test</p>
<input value="Hit enter to change value" id="val" onchange="changeVal(this)">
I have no plan what the point of your question is but maybe you look for this...
var foo = document.getElementById('id_of_input_field').value; // get
document.getElementById('id_of_input_field').value = 'value to set'; // set
I think this is what you are looking for
Code
<input value="variable" id="val" onchange="changeVal(this)">
TS
onchange(this){
let var = event.target.getElementsByTagName('input').value;
}

Javascript Regex Email Validation in Razer view

I am attempting to validate an email input that is created with an HTML helper class. The 'validateForm' method is being called properly everytime, but the if statement keeps failing. My two best theories are that my Regex, that I found here, is off due to me having to escape the '#' characters, or I'm not properly comparing it.
Thanks always!
Javascript:
function validateForm() {
var isValid = true;
var errorMessage = "";
var emailRegExp = /^(([^<>()[\]\\.,;:\s##\"]+(\.[^<>()[\]\\.,;:\s##\"]+)*)|(\".+\"))##((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var x = document.forms["Update"]["complaint.Responsible"].value;
if (x === null || x === "" || !emailRegExp.test(x)) {
errorMessage += "A valid 'Responsible' was not entered<br/>";
document.getElementById("Responsible").style.borderColor = '#F00';
alert("No! >:(");
isValid = false;
}
return isValid;
}
Form CSHTML:
#Html.TextBoxFor(model => Model.complaint.Responsible, new { #Class = "txtLong" })
Form HTML:
<form name="Update" onsubmit="return validateForm()" method="post" id="formBody" enctype="multipart/form-data">
<input class="txtLong" id="complaint_Responsible" name="complaint.Responsible" type="text" value="sdbsv rszaer gse er">
Update:
This is why I can't use a single '#' symbol
(one line - as is in code)
The ## is telling the regex engine that you expect two # symbols. Replace it with the pattern below:
var emailRegExp = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

javascript input.focus() is not working in firefox 23

I am using this code..
Error is showing but focus is not working in firefox. As this code is working in IE, i can't say this code is completely wrong.
<form name="frm" action="search.php" method="post">
<input type="text" name="search" onblur="return check();"/>
<input type="submit" name="submit" />
<strong id="err"></strong>
</form>
I am using this string in external javascript.
This code is in valid.js
function check()
{
var item=frm.search;
var errr=document.getElementById('err');
if(item.value.length<3)
{
item.focus();
errr.innerHTML="Entered String is very short";
return false;
}
}
Please reply me as soon as possible.
try this one
function check()
{
var item = document.forms['frm'].elements['search'];
var errr=document.getElementById('err');
if(item.value.length<3)
{
errr.innerHTML="Entered String is very short";
setTimeout(function() {
item.focus()
}, 10);
return false;
}
}
demo jsfiddle http://jsfiddle.net/ff4vW/
Its good if you use document.getElementById()
But if you are using name
Then you should use
var item = document.forms['frm'].elements['search'];
var item = document.getElementsByName('search')[0];

Categories

Resources