There is a JavaScript function in SharePoint called "PreSaveAction" that is fired just before the item is validated and saved. You can use this function to call your function. For example:
function PreSaveAction(){
var itemTitle = $("input[title='GUID']").val();
if (itemTitle.length < 1) {
alert("The Title Field Cannot Be Blank");
$("input[title='Total']").attr("style", "border: solid 1px #ff4c42 !important");
return false;
}
}
Please note, you should do complete validation of the item because if the item fails server side validation your function will have run but the item will not be saved (causing the user to fix the validation error, hit save again, and running your function again). This may not be important if you're only doing validation, but it's worth noting.
Answer from Taran Goel on Stack ExchangeThere is a JavaScript function in SharePoint called "PreSaveAction" that is fired just before the item is validated and saved. You can use this function to call your function. For example:
function PreSaveAction(){
var itemTitle = $("input[title='GUID']").val();
if (itemTitle.length < 1) {
alert("The Title Field Cannot Be Blank");
$("input[title='Total']").attr("style", "border: solid 1px #ff4c42 !important");
return false;
}
}
Please note, you should do complete validation of the item because if the item fails server side validation your function will have run but the item will not be saved (causing the user to fix the validation error, hit save again, and running your function again). This may not be important if you're only doing validation, but it's worth noting.
Use the PreSaveAction() that all forms check for before saving. true = validation succeeds and save the form, false = validation fails, alert the user.
<script type="text/javascript">
function PreSaveAction(){
var name = $("#name").text();
if(!name)
{
var div = document.getElementById('errorMessage');
div.innerHTML = 'Error Message goes here';
div.show();
return false;
}
return true;
}
</script>
Videos
First of all I would recommend you using id instead of class to get querySelector, because, with id you will get a single element. but with class you may get list of elements.
After, I think you are appending in wrong way the child, you should do next:
usernameError.appendChild(usernameError);
Or you can use innerHtml.
The best way to do that:
Normally, if you have a fixed text to show or hide, you don’t need to create it dynamically and append to a div.
You can create a class to hide it.
html:
<div class="username-error hide">
Please add your username
</div>
css:
.hide{
display:none;
}
So, when you want to show the error just remove this class from your error element (div), otherwise add it.
js:
if(!username){
element.classList.remove("hide");
}
let username = document.querySelector("#username");
let password = document.querySelector("#username");
let usernameError = document.querySelector(".username-error");;
let createdEl = document.createElement("div");
let createdE2 = document.createTextNode("Please add your username");
createdEl.appendChild(createdE2);
if(!username.value){
usernameError.appendChild(createdEl);
}
}
Use this instead
You can use the errorPlacement option to pass a callback like this: http://jsfiddle.net/cMhQ7/
I've used a standard of the div id being the input element's name concatenated with a _validate suffix but you can change as you wish.
HTML
<form id="employment-application" method="post">
<input name="full_name" type="text" />
<div id="full_name_validate"></div>
<input type="submit" />
</form>
Javascript
$(function validate() {
var rules = {
rules: {
full_name: {
minlength: 2,
maxlength: 50,
required: true
},
},
errorPlacement: function (error, element) {
var name = $(element).attr("name");
error.appendTo($("#" + name + "_validate"));
},
};
$('#employment-application').validate(rules);
});
If only want to change the default placement to certain elements, you can use this improvement. This implements the default behaviour of validate script
errorPlacement: function(error, element){
var name = $(element).attr("name");
var $obj = $("#" + name + "_validate");
if($obj.length){
error.appendTo($obj);
}
else {
error.insertAfter(element);
}
},
A more pure jQuery approach would be as shown below
jQuery Code
if (name == '' || email == '' || mobile == '' || password == '' || cpassword == '') {
var errName = $("#name"); //Element selector
errName.html("Please enter name"); // Put the message content inside div
errName.addClass('error-msg'); //add a class to the element
}
CSS:
.error-msg{
background-color: #FF0000;
}
Update:
You can even combine the jQuery methods on any selector. Whenever we apply a jQuery menthod on any selector, it returns a "this" pointer, so we can combine multiple methods and apply them to a selector using a single statement. This is called "chaining"
Read more here: http://www.w3schools.com/jquery/jquery_chaining.asp
if (name == '' || email == '' || mobile == '' || password == '' || cpassword == '') {
$("#name").html("Please enter name")
.addClass("error-msg"); // chained methods
}
if (name == '' || email == '' || mobile == '' || password == '' || cpassword == '') {
var errName = $("#name"); //get element by ID
errName.append("Please enter name"); //append information to #name
errName.attr("style", "background-color: red;"); //add a style attribute
}
Edit: or you could do it like so:
if (name == '' || email == '' || mobile == '' || password == '' || cpassword == '') {
var errName = $("#name"); //get element by ID
errName.append("Please enter name"); //append information to #name
errName.attr("class", "alert"); //add a class to the element
}
Then you will have an .alert class. This makes it possible for you to use this class in your CSS file.
.alert {
background-color: #FF0000;
}
Your code to display message is correct, problem here is that the form is submitted when the button is clicked. You need to prevent the default action when the condition is not fulfilled.
I would recommend you to use form's submit event, when false is returned it will prevent the default action (form being submitted).
<head>
<script>
function myFunction() {
var a = document.forms["login"]["uname"].value;
var b = document.forms["login"]["pwd"].value;
if (a == "" || b == "") {
error = "All fields must be entered.";
document.getElementById("errorid").innerHTML = error;
return false;
}
return true;
}
</script>
</head>
<body>
<form name="login" action="" onsubmit="return myFunction()">
<b>Enter username:</b>
<input type="text" name="uname" />
<br />
<b>Enter password:</b>
<input type="password" name="pwd" />
<br />
<p id="errorid"></p>
<input type="submit" />
</form>
</body>
</html>
You can add the required attribute to the input if the user must enter it in order to submit the form you can do this like :<input type='text' required>
In this way you dont have to worry about the user not filling the field. HTML5 will automatically take care of that. Try it
If no error , hide that div. In 'er' div, write style='display:none'
<div id='er' style='display:none'><?php echo $er; ?></div>
Here, if error. Show That div. Otheriwse hide that div.
$(document).ready(function() {
$('#submit').click(function() {
var firstname = document.getElementById('fn').value;
var lastname = document.getElementById('ln').value;
var password = document.getElementById('pswd').value;
if (firstname.length < 2 || firstname.length > 11) {
$('#er').show();
$('#er').html('First name must be between 1 to 11 characters long');
return false;
}
else if (lastname.length < 2 || lastname.length > 11) {
$('#er').show();
$('#er').html('Last name must be between 1 to 11 characters long');
return false;
}
else if (password == "") {
$('#er').show();
$('#er').html('Fill your password');
return false;
}
else {
$('#er').hide();
}
});
});
Write a css selector for the element when empty, and set display : none
div {
background-color: lightblue;
margin: 10px;
display: inline-block;
height: 20px;
}
.demo:empty {
display: none;
}
<div class="demo">One</div>
<div class="demo"></div>
<div class="demo">Other</div>
You don't need to take care of anything else, when in JS you set the content to nothing, it will disappear
Support is quite good, only missing in IE8 http://caniuse.com/#feat=css-sel3