Javascript live validation - javascript

I have a very simple HTML/JavaScript form that I am working on for coursework, I have got it to work however i would like it to validate the input as the user types (my validation appears below the text field) how can I achieve this? My code is as follows:
<!DOCTYPE html>
<html>
<head>
<script class="jsbin" src="http:ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"> </script>
<meta charset=utf-8 />
<title>Email Validation</title>
</head>
<body>
<form onsubmit='validate(); return false;'>
<p>Enter an email address:</p>
<input id='email' placeholder="example#example.com" size="21">
<button type='submit' id='validate'>Submit</button>
</form>
<br />
<h2 id='result'></h2>
<script>
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\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,}))$/;
return re.test(email);
}
function validate() {
$("#result").text("");
var email = $("#email").val();
if (validateEmail(email)) {
$("#result").text(email + " is valid");
$("#result").css("color", "green");
} else {
$("#result").text(email + " is not valid");
$("#result").css("color", "red");
}
return false;
}
$("form").bind("submit", validate);
</script>
</body>
</html>

For methods not using jQuery, in case you're interested, there's another Stack Overflow question here: On Input Change Event.
There are many ways to do what you want listed there, but in this case you could do something like this:
var input = document.querySelector('input');
input.addEventListener('input', function()
{
// Check input.value for what you're looking for here
});
See the jsFiddle that Drew Noakes' made in that other page for an example.
But, since you're using jQuery, then Nicholas Kyriakides's suggestion is the way to go.

Related

Javascript form validating and prevent submission

How can I prevent submision if in my text field are entered just specific characters <>{} and not all of special characters? I'm losing my mind :/
I think you are looking for regex expression. Let me know if it's helpful
$(":input").each(function() {
var input = $(this).val();
var regex = new RegExp("^[a-zA-Z]+$");
if(regex.test(input)) {
alert("true");
} else {
alert("false");
return false;
}
})
I don't have an exact answer as you didn't post any sample code. I can only point you to this article https://javascript.info/bubbling-and-capturing which explain how events bubbling works. A solution will be to use event.stopPropagation() in case the validation doesn't pass.
Here an working ex:
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
const regex = new RegExp('^[a-zA-Z]+$');
const input = document.forms['someForm']['somename'].value;
if (regex.test(input)) {
console.log("true");
} else {
console.log("false");
return false;
}
}
</script>
</head>
<body>
<form name="someForm" onsubmit="return validateForm()" method="post">
Name: <input type="text" name="somename">
<input type="submit" value="Submit">
</form>
</body>
</html>

How to select and run this function onload?

So I have this working codeblock in my script to replace the decimal seperator from comma "," into period "." ,when editing a form. Because in this region the decimal seperator comma is normal I also want the values to be displayed like this 1,99€ so I reverted the working function. The selected fields should change on load. When the form gets submitted I will cange it back again. For this example I show you only one of the fields.
The value="1.5" gets loaded from the Magento-Backend the wrong way, which is another story:
I included onload:"function(event)"
and window.onload = function(); to show two my attempts to adress this function from jQuery: jQuery('form').on('change', '#price', function(event) I also need to know how to remove the .on('change' part. First time using Js und jQuery. I really tried everything.
<html>
<body onload="function(event)">
<form>
<input id="price" value="1.5">
</form>
</body>
</html>
<script>
window.onload = function();
jQuery('form').on('change', '#price', function(event) {
event.preventDefault();
if (jQuery('#price').val().includes('.')) {
var varwithpoint = jQuery('#price').val();
varwithcomma = varwithcomma.replace(",",".");
jQuery('#price').val(varwithpoint);
}
else {
console.log('no dot to replace');
}
});
</script>
There were a few parts of the code which didn't seem to be working as intended, so below is a basic example of code that will convert the "," to a "." if stored in the input "price", and check this after each change of the value;
function convert_price(){
var this_price = $("#price").val();
if (this_price.includes(',')) {
this_price = this_price.replace(",",".");
$('#price').val(this_price);
} else {
console.dir('no dot to replace');
}
}
convert_price();
$("#price").on("change",convert_price);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<html>
<body>
<form>
<input id="price" value="1,5">
</form>
</body>
</html>
I have called "init" the function that attaches the change event to the input file, I also changed the parameters passed to the on function
function init(){
var input = jQuery('#price');
input.on('change', function(event) {
event.preventDefault();
var valueInInput = input.val();
if (valueInInput.includes('.')) {
var varwithcomma = valueInInput.replace(",",".");
input.val(varwithcomma);
} else {
console.log('no dot to replace');
}
});
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body onload="init()">
<form>
<input id="price" value="1.5">
</form>
</body>
</html>

Javascript check textarea for specific text

I have a text area on a simple website that I would like to check for specific text. The text that I would like to check for are html tags. It works when I put the tags right next to each other. I want to make sure that the text area has the tags but with any number of spaces or breaks. Thanks in advance!
Here is my full code:
<!DOCTYPE html>
<html>
<head>
<script language="JavaScript" type="text/javascript">
<!--
function checkform ( form )
{
// see http://www.thesitewizard.com/archive/validation.shtml
// for an explanation of this script and how to use it on your
// own website
// ** START **
if (form.email.value == "<html><head></head><body></body></html>") {
var node = document.getElementById("grr");
node.innerHTML = "<p>" + "Correct!" + "</p>";
form.email.focus();
return false ;
}
// ** END **
return true ;
}
//-->
</script>
</head>
<body>
<form action="#" method="post" onsubmit="return checkform(this);">
<textarea id="email" type="text" rows="5" columns="5"></textarea>
<input type="submit" value="submit">
</form>
<p id="p1">Hello World!</p>
<script>
document.getElementById("p1").innerHTML="New text!";
</script>
<div id="grr">Text</div>
</body>
</html>
There's not many good ways to do this. Generally you should parse HTML in the browser and return the HTML string, as that would solve the issue for the most part, but you can't really insert an entire document with <html>, <head> tags and everything into another element, so you're probably left with a regex solution, something like this
function checkform(form) {
var div = document.createElement('div'),
email = document.getElementById('email');
if (email.value.replace(/\>\s+\</g, '><').trim() == "<html><head></head><body></body></html>") {
var node = document.getElementById("grr");
node.innerHTML = "<p>" + "Correct!" + "</p>";
email.focus();
return false;
}
return true;
}
FIDDLE

check text box value is according to a prefix

I have text box.
Users can enter Student Id into that.
Student id is in this format DIP0001.
First three letters should be DIP and the remaining 4 digits should be numeric and can only upto 4 characters.
So how can I check whether entered data is in this format using javascript.
Please help.....
You could build a regular expression pattern and test it against that value to see if it matches that exact pattern.
HTML FILE:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Title</title>
</head>
<body>
<label for="studentId">Student ID</label>
<input id="studentId" type="text">
<button id="btn" type="button">Validate</button>
// Embedded script so that you don't have to load an external file
<script>
var input = document.getElementById('studentId');
var btn = document.getElementById('btn');
var pattern = /DIP+\d{1,3}/g;
btn.addEventListener('click', function(){
if(pattern.test(input.value)) {
alert('It enter code here`atches!');
}else {
alert('It does not match!');
}
});
</script>
</body>
</html>
JS FILE:
// This pattern looks something like this: DIP0000
var pattern = /DIP+\d{1,3}/g;
// studentId is the ID of the input field that contains the Student ID
var studentIdInput = document.getElementById('studentId');
// Check the pattern against the provided Student ID
if(pattern.test(studentIdInput.value)) {
alert('It matches the pattern!');
}
EDIT 1: I have built the functionality in the following JSFiddle: http://jsfiddle.net/vldzamfirescu/QBNrW/
Hope it helps!
EDIT2: I have updated the JSFiddle to match any other combinations up to 4 digits; check it out: http://jsfiddle.net/vldzamfirescu/QBNrW/1/ Let me know if it solved your problem!
try this code
<html>
<head>
<script>
function validate(val) {
if (val.value != "") {
var filter = /^[DIP]|[dip]+[\d]{1,4}$/
if (filter.test(val.value)) { return (true); }
else { alert("Please enter currect Student Id"); }
val.focus();
return false;
}
}
</script>
</head>
<body>
<input id="Text1" type="text" onblur="return validate(this);" />
</body>
</html>
Use Regular Expresions.
If found a valid Student ID, the pattern will return true:
function validateStudentId(id) {
var re = /DIP[0-9]{4}/;
return re.test(id);
}
// Edited for use with a click event:
document.getElementById('button').addEventListener('click', function(){
if( validateStudentId(document.getElementById('textBox').value) ){
alert('correct');
}else{
alert('invalid ID');
}
});

Validating an e-mail address using regex

I am trying to validate e-mail addresses on my website and I have been trying to code up a demo of how e-mail validation would work with JavaScript. What I am trying to do is pass in the value of the e-mail address entered by the user to the validateEmail function and then print out 'valid' or 'invalid' in the div with the id 'result'. Because I am relatively new to JavaScript, I am not sure how to accomplish this and was wondering it if someone could show me an example of how to do this?
<head>
<title>Practice</title>
<script type="text/javascript">
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\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,}))$/;
return re.test(email);
}
</script>
</head>
<body>
<form action="post" method="practice.php">
e-mail: <input id="email" type="text" onblur="validateEmail(execute(document.getElementById('email').value))" />
<div id="result"></div>
</form>
</body>
First of all you don't need to use execute method and can get value from this context:
validateEmail( this.value )
Then modify your function to print result:
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\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,}))$/;
if(re.test(email)) {
document.getElementById('result').innerHTML = 'valid';
} else {
document.getElementById('result').innerHTML = 'invalid';
}
}

Categories

Resources