How to validate ZK Textbox by using HTML5+CSS3 validation? - html

I'm using ZK7, HTML5, CSS3 and I'm trying to validate below zk textbox element if it is a valid email:
<form id="validation-form">
<fieldset>
<div class="form-group">
<label class="block clearfix" for="email">
<span class="block input-icon input-icon-right">
<z:textbox id="emailInput" type="email" class="form-control" placeholder="${labels.login.email}"/>
<i class="icon-envelope"></i>
</span>
</label>
</div>
<div class="clearfix">
<button id="forgotPassword" type="button" class="width-35 pull-right btn btn-sm btn-danger">
<i class="icon-lightbulb"></i>
${labels.send}
</button>
</div>
</fieldset>
</form>
Here is the script:
<script type="text/javascript">
jQuery(function($) {
$('[data-rel=tooltip]').tooltip();
$(".select2").css('width','200px').select2({allowClear:true})
.on('change', function(){
$(this).closest('form').validate().element($(this));
});
var $validation = false;
//documentation : http://docs.jquery.com/Plugins/Validation/validate
$('#validation-form').validate({
errorElement: 'div',
errorClass: 'help-block',
focusInvalid: false,
rules: {
email: {
required: true,
email:true
}
},
messages: {
email: {
required: "Please provide a valid email.",
email: "Please provide a valid email."
}
},
invalidHandler: function (event, validator) { //display error alert on form submit
$('.alert-danger', $('.login-form')).show();
},
highlight: function (e) {
$(e).closest('.form-group').removeClass('has-info').addClass('has-error');
},
success: function (e) {
$(e).closest('.form-group').removeClass('has-error').addClass('has-info');
$(e).remove();
},
errorPlacement: function (error, element) {
if(element.is(':checkbox') || element.is(':radio')) {
var controls = element.closest('div[class*="col-"]');
if(controls.find(':checkbox,:radio').length > 1) controls.append(error);
else error.insertAfter(element.nextAll('.lbl:eq(0)').eq(0));
}
else if(element.is('.select2')) {
error.insertAfter(element.siblings('[class*="select2-container"]:eq(0)'));
}
else if(element.is('.chosen-select')) {
error.insertAfter(element.siblings('[class*="chosen-container"]:eq(0)'));
}
else error.insertAfter(element.parent());
},
submitHandler: function (form) {
},
invalidHandler: function (form) {
}
});
$('#modal-wizard .modal-header').ace_wizard();
$('#modal-wizard .wizard-actions .btn[data-dismiss=modal]').removeAttr('disabled');
})
</script>
It is working when I change z:textbox to html input as:
<input id="emailInput" type="email" class="form-control" placeholder="${labels.login.email}"/>
How should I do the same by using zk textbox?

I'm not 100% sure if this is what you wanted, cause your question has a lot of javascript, jquery and the first code doesn't really looks like zk(only your internationalization is familiar).
If you use zk you can do the following :
<textbox value="#bind(vm.email)" id="email"
constraint="/.+#(.+\.[a-z]+|)/: Please enter a valid e-mail address"
type="email" placeholder="enter email" />
I did put a simpel email constraint there, but you can change the constraint to what you want.
Hope this helps you.

There is this nice example of integrating jquery masks with zk.
For client side validation this should be fine.
In addition, ZK offers form validation as well as constraints for InputElements

Related

Ajax Form Submit using jQuery

I am working with a form that I want to submit with ajax to a api that sends email to the email mentioned in it and the api was working in postman with raw data but I can't get it to work with the form using jQuery and ajax so if you guys can tell me why my function is not working and sending the email it will be of great help to me
Function for form submit:-
$(function() {
$("#contactForm input,#contactForm textarea").jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
// additional error messages or events
},
submitSuccess: function($form, event) {
event.preventDefault(); // prevent default submit behaviour
// get values from FORM
var name = $("input#name").val();
var email = $("input#email").val();
var phone = $("input#phone").val();
var message = $("textarea#message").val();
var firstName = name; // For Success/Failure Message
// Check for white space in name for Success/Fail message
if (firstName.indexOf(' ') >= 0) {
firstName = name.split(' ').slice(0, -1).join(' ');
}
$this = $("#sendMessageButton");
$this.prop("disabled", true); // Disable submit button until AJAX call is complete to prevent duplicate messages
$.ajax({
"url": "http://178.18.243.33:8089/email/sendmailusingtemplate",
"method": "POST",
"timeout": 0,
"headers": {
"Content-Type": "application/json"
},
"data": JSON.stringify({
"to": "nkulhari96#gmail.com",
"cc": "services#gmail.com",
"template": "contact_us_001",
"name": "name",
"email": "email",
"mobile": "phone",
"message": "message"
}),
},
cache: false,
success: function() {
// Success message
$('#success').html("<div class='alert alert-success'>");
$('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-success')
.append("<strong>Your message has been sent. </strong>");
$('#success > .alert-success')
.append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
error: function() {
// Fail message
$('#success').html("<div class='alert alert-danger'>");
$('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-danger').append($("<strong>").text("Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!"));
$('#success > .alert-danger').append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
complete: function() {
setTimeout(function() {
$this.prop("disabled", false); // Re-enable submit button when AJAX call is complete
}, 1000);
}
});
},
filter: function() {
return $(this).is(":visible");
},
});
$("a[data-toggle=\"tab\"]").click(function(e) {
e.preventDefault();
$(this).tab("show");
});
});
/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
$('#success').html('');
});
Code for Form:-
<form name="sentMessage" id="contactForm" novalidate="">
<div class="control-group form-group">
<div class="controls">
<input type="text" placeholder="Full Name" class="form-control" id="name" required="" data-validation-required-message="Please enter your name.">
<p class="help-block"></p>
</div>
</div>
<div class="control-group form-group">
<div class="controls">
<input type="tel" placeholder="Phone Number" class="form-control" id="phone" required="" data-validation-required-message="Please enter your phone number.">
<div class="help-block"></div></div>
</div>
<div class="control-group form-group">
<div class="controls">
<input type="email" placeholder="Email Address" class="form-control" id="email" required="" data-validation-required-message="Please enter your email address.">
<div class="help-block"></div></div>
</div>
<div class="control-group form-group">
<div class="controls">
<textarea rows="5" cols="100" placeholder="Message" class="form-control" id="message" required="" data-validation-required-message="Please enter your message" maxlength="999" style="resize:none"></textarea>
<div class="help-block"></div></div>
</div>
<div id="success"></div>
<!-- For success/fail messages -->
<button type="submit" class="btn btn-primary" id="sendMessageButton">Send Message</button>
</form>

How to check password using RegEx using jquery and without keyup function

I want to make a signup form in which user type password which contains combination of alphabet,letter and length > 6 otherwise form will not submit
here I have shown function specifically for password only but i have other function for other input types and they are working properly but it is not.
$('#password').hide();
var password = false;
$('#user_password').focusout(function() {
check_password();
});
function check_password() {
var password = new RegExp(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s).{8,15}$/);
var password_length = $('#user_password').val().length;
if (password.test($("#user_password").val()) && password_length > 6) {
alert("hello");
$('#password').hide();
} else {
$('#password').html('Password should be more than 6 character and should contain a letter and number');
$('#password').show();
password = true;
}
}
$('#signupfrm').submit(function() {
password = false;
check_password();
if (password == false) {
return true;
} else {
return false;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form role="form" name="signupfrm" id="signupfrm" method="post" action="<?php $_SERVER['PHP_SELF'] ?>">
//other input types above password input type
<input type="password" class="form-control" placeholder="Password..." name="user_password" id="user_password" required="">
<span id="password">
</span>
<button type="submit" class="btn btn-login" name="signup" id="signup" value="Signup">Create My Account</button>
</form>
You likely meant to do this
But you need to fix your regex https://regex101.com/r/ND19JO/1
I suggest this:
^(?=.{6,})(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%^&+=]).*$
6 chars one lowerCase, one upperCase and one special char
const passwordRe = new RegExp(/^(?=.{6,})(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%^&+=]).*$/);
const check_password = function() {
const pw = $('#user_password').val();
const pwOK = passwordRe.test(pw);
$('#pwError').toggle(!pwOK);
return pwOK;
}
$(function() {
$('#user_password').focusout(check_password)
$('#signupfrm').on("submit", function(e) {
if (!check_password()) e.preventDefault();
})
})
#pwError {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form role="form" name="signupfrm" id="signupfrm" method="post" action="">
<input type="password" class="form-control" placeholder="Password..." name="user_password" id="user_password" value="bla" required="">
<span id="pwError">Password should be more than 6 character and should contain a letter and number</span>
<button type="submit" class="btn btn-login" name="signup" id="signup" value="Signup">Create My Account</button>
</form>
If you have the correct regex, you don't have to test separately for the length:
var password = /^(?=.*\d)(?=.*[a-zA-Z])(?!.*\s).{7,15}$/;
It seems you also do not allow white space in your password. The way to prevent the form from submitting is to execute event.preventDefault() in your submit handler if the password is invalid. So the function check_password needs to return a flag that will be checked. I have removed the code that hides and unhides the password field to reduce the code to its essence:
function check_password() {
var password = /^(?=.*\d)(?=.*[a-zA-Z])(?!.*\s).{7,15}$/;
if (password.test($("#user_password").val())) {
return true;
}
else {
console.log('Password should be more than 6 character and should contain a letter and number and no spaces');
return false;
}
}
$(function() {
$('#signupfrm').submit(function() {
if (!check_password(event)) {
event.preventDefault();
}
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form role="form" name="signupfrm" id="signupfrm" method="post" action="<?php $_SERVER['PHP_SELF'] ?>">
<input type="password" class="form-control" placeholder="Password..." name="user_password" id="user_password" required="">
<span id="password">
</span>
<button type="submit" class="btn btn-login" name="signup" id="signup" value="Signup">Create My Account</button>
</form>
Note that you should only attempt to create the submit handler once you are sure that the document's elements have been created, i.e. element id signupform in this case. That is why that code is placed in a jQuery.ready() block (or its shortcut version). See .ready().

Autocomplete input suggestions

I'm trying to set up an input with autocomplete places list. I want to use Here autosuggest tool.
https://developer.here.com/documentation/geocoding-search-api/dev_guide/topics/endpoint-autosuggest-brief.html
For this I did this code :
<div class="autocomplete input-group has-warning">
<input id="search-where" name="w" type="text" class="form-control input-lg" placeholder="A quel endroit?" required="required" value="" autocomplete="on" onkeyup="mySearch(this.value)" />
<span class="input-group-btn">
<button type="submit" class="btn btn-lg btn-warning"><span class="glyphicon glyphicon-screenshot"></span></button>
</span>
</div>
{literal}
<script type="text/javascript">
function mySearch(e){
$.ajax({
url: "https://places.ls.hereapi.com/places/v1/suggest",
type: 'GET',
data: {
at: '44.771079,5.742806',
q: 'savoie',
app_id: '2FXOZOY',
app_code: 'b_9sMKgQmSjWUj1rlyY0wI'
},
headers : { "Authorization": "Bearer" + $('b_9sMKgQ5qzJF0SusExJJx9irrHHimSjWUj1rlyY0wI').val()},
beforeSend: function(xhr){
xhr.setRequestHeader('Accept', 'application/json');
},
success: function (data) {
alert(JSON.stringify(data));
}
});
$( "#search-where" ).autocomplete({
source: mySearch
});
}
</script>
{/literal}
But I get this error when I try to write in the input :
I'm clearly completely lost ... If anyone can help me it would be much appreciated.
Thanks for reading me anyway
I think you are doing an XMLHttpRequest to a different URL than the page you are on. In such scenarios, browser blocks it completely giving CORS error due to security reasons. There are a lot of ways to set this. A tutorial is available here.

ng-model vs ngModel - breaks form

New to angular, new to life:
I have a small email form.
This works:
<form method="post" name="form" role="form" ng-controller="contactForm" ng-submit="form.$valid && sendMessage(input)" novalidate class="form-horizontal">
<p ng-show="success"><b>We received your message</b></p>
<p ng-show="error">Something wrong happened!, please try again.</p>
<label for="name">Name:</label><br>
<input type="text" id="name" name="name" ng-model="input.name" required><br>
<label for="email">Email:</label><br>
<input type="email" id="email" name="email" ng-model="input.email" required><br>
<label for="messsage">Message:</label><br>
<textarea id="messsage" name="message" ng-model="input.message" ngMaxlength='2000' required></textarea><br>
<button type="submit" name="submit" ng-disabled="error" value="submit">Submit</button>
</form>
This does not work:
<form method="post" name="form" role="form" ng-controller="contactForm" ng-submit="form.$valid && sendMessage(input)" novalidate class="form-horizontal">
<p ng-show="success"><b>We received your message</b></p>
<p ng-show="error">Something wrong happened!, please try again.</p>
<label for="name">Name:</label><br>
<input type="text" id="name" name="name" ngModel="input.name" required><br>
<label for="email">Email:</label><br>
<input type="email" id="email" name="email" ngModel="input.email" required><br>
<label for="messsage">Message:</label><br>
<textarea id="messsage" name="message" ngModel="input.message" ngMaxlength='2000' required></textarea><br>
<button type="submit" name="submit" ng-disabled="error" value="submit">Submit</button>
</form>
for the 2 inputs and the textarea if I use 'ng-model' the email sends, but when the page loads, the form loads invalid.
If i use 'ngModel' the form loads clean, but the email wont submit.
controller here:
app.controller("contactForm", ['$scope', '$http', function($scope, $http) {
$scope.success = false;
$scope.error = false;
$scope.sendMessage = function( input ) {
$http({
method: 'POST',
url: 'processForm.php',
data: input,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})
.success( function(data) {
if ( data.success ) {
$scope.success = true;
$scope.input.name="";
$scope.input.email="";
$scope.input.message="";
} else {
$scope.error = true;
}
} );
}
You can see it live here:
http://smartestdiner.com/Bethel/indexx.html#/contact
Warning:
There is some annoying red background
.ng-invalid{
background-color:red;
}
}]);
That's how we know it is loading invalidly.
The annoying red background is the form, since you have a very generic rule set by .ng-invalid, the class will be set on the form as well. You would need to make it more specific for the inputs and controls within the form.
Example:
input.ng-invalid,
textarea.ng-invalid {
background-color:red;
}
Or just reset rule for form.ng-invalid
To add on there is nothing called ngModel it is ng-model. using the former one doesn't do anything but adds a dummy attribute on the element, it has no effect. It is angular way of directive naming, since html is case insensitive the one way angular can identify the directive from attribute or element name (based on the restriction). It converts it to camelCasing to evaluate and process respective directive (or directives attribute bindings). When you do not have ng-model specified and if the form or control does not have novalidate attribute, then the browser's HTML5 validation kicks in that is what you see as inconsistency. Using HTML5 novalidate attribute makes sure no native validation happens on the form.
ng-model is when u write the view (html part).
ngModel is used when one write a custom directive. It is placed in the "require:" param so that u can access,
variables like ngModel.$modelValue
ngModel.$modelValue will have the latest content which has been typed by the user at realtime. So, it can be used for validations, etc.
View code:-
<!doctype html>
<html ng-app="plankton">
<head>
<script src="/bower_components/angular/angular.min.js"></script>
<script src="/scripts/emailing/emailing.directive.js"></script>
</head>
<body ng-controller="EmailingCtrl">
<div>
<label>Enter Email: </label>
<emailing id="person_email" ng-model="email_entered"></emailing>
</div>
</body>
</html>
Custom directive:-
(function() {
'use strict';
angular.module('plankton', [])
.directive('emailing', function emailing(){
return {
restrict: 'AE',
replace: 'true',
template: '<input type="text"></input>',
controllerAs: 'vm',
scope: {},
require: "ngModel",
link: function(scope, elem, attrs, ngModel){
console.log(ngModel);
scope.$watch(function(){ return ngModel.$modelValue;
}, function(modelValue){
console.log(modelValue);//awesome! gets live data entered into the input text box
});
},
};
})
.controller('EmailingCtrl', function($scope){
var vm = this;
});
})();
This has been plunked here:- here

Send JSON from HTML form with NODEJS backend

I haven't done front end HTML since I was 10 and that was drag and drop frontpage stuff. with static pages. As a result I'm really rusty.
What I need to do is put together a web client for a rest API that I wrote in NodeJS. My question is how, do you send a request from a form (say a log in form) to the server where the body of the POST request is a JSON of the email/password?
HTML form:
<form id="loginForm" action="" method="" class="form-horizontal">
<fieldset>
<legend>Log in</legend>
<div class="control-group">
<label class="control-label" for="email">Email</label>
<div class="controls">
<input type="text" class="input-xlarge" id="email">
</div>
</div>
<div class="control-group">
<label class="control-label" for="password">Password</label>
<div class="controls">
<input type="password" class="input-xlarge" id="password">
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary">Save changes</button>
<button class="btn">Cancel</button>
</div>
</fieldset>
</form>
I suggest a lot of reading. To get you started with a very basic example, though, you will find a page with a sample form below that does what you need. You just need to replace the string your URL here with the actual URL you expect will be doing the handling.
The serializeObject() function was taken from here: Convert form data to JavaScript object with jQuery
<html>
<body>
<form id="loginForm" action="" method="">
Username: <input type="text" name="username" id="username" /> <br />
Password: <input type="password" name="password" id="password" /> <br />
<input type="submit" />
</form>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(function () {
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$("#loginForm").bind("submit", function(evt) {
console.log(JSON.stringify($("#loginForm").serializeObject()));
$.ajax({
url: "your URL here",
type: "POST",
contentType: "application/json",
data: JSON.stringify($("#loginForm").serializeObject()),
success: function (data, textStatus, jqXHR) {
// do something with your data here.
},
error: function (jqXHR, textStatus, errorThrown) {
// likewise do something with your error here.
}
});
return false;
});
});
</script>
</body>
</html>
The problem with your form is that input elements don't have name attributes. The name attribute is essential in many ways, so I would fix your html by setting each element's name attribute to the same value as its id attribute. The serializeObject function relies on form elements having names.
Here's an example using jQuery:
<form name="myform" action="#" method="POST">
Username: <input type="text" id="user" name="username"/><br/>
Password: <input type="password" id="pass" name="password"/>
<input type="submit" id="login" value="Login"/>
</form>
<script type="text/javascript">
var user=$('#user').val(), pass=$('#pass').val();
$('login').bind('click', function() {
$.ajax('/my/url', {
type: 'POST',
contentType: 'text/json',
data: JSON.stringify({username:user, password:pass}),
complete: function() { /* Do something with the response. */ }
});
return false; // Prevent form submit.
});
</script>
This might help you. Here is the form below: If you notice there is action and method if you don't know what these are, just go on and search for it. Action is the target server file that handles the information you send and method is get which is retrieving not updating.
Existing Users Username: Password:
Keep Me
Logged In
Here is the jquery part to handle the ajax call:
$.ajax({
type: "GET",
url: action,
data: form_data,
success: function(response)
{
if($.trim(response) == 'success')
window.location.replace("profile.php");
else
$("#result").html(response);
}
});
return false; });
});