I have a form using Tinymce, I need to check if it only contains space.
I try using this function
function validation_form()
{
var content = tinyMCE.get('main-ment').getContent().replace(' ','');
if(content == "" || content == null || content == '<p> </p>') {
return false;
}
}
But it returns true when I input several spaces and submit, I want it to return false instead.
Can anyone help me? Thanks,
I have a form using Tinymce, I need to check if it only contains space.
I try using this function
function validation_form()
{
var content = tinyMCE.get('main-ment').getContent().replace(' ','');
if(content == "" || content == null || content == '<p> </p>') {
return false;
}
}
But it returns true when I input several spaces and submit, I want it to return false instead.
Can anyone help me? Thanks,
Share Improve this question edited Jun 28, 2016 at 5:39 TuringTux 5912 gold badges13 silver badges28 bronze badges asked Jun 28, 2016 at 4:37 Henry BuiHenry Bui 7132 gold badges7 silver badges24 bronze badges 2-
"But it return true when..." - No it doesn't. The function shown returns either
false
orundefined
, it never returnstrue
. – nnnnnn Commented Jun 28, 2016 at 4:45 - sr, not return true. But if it don't return false, the form will submit. I have called it in form by onsubmit='return validation_form()' – Henry Bui Commented Jun 28, 2016 at 4:50
4 Answers
Reset to default 7use $.trim ,
it is clean and readable.
function validation_form()
{
var content = $.trim(tinyMCE.get('main-ment').getContent({format: 'text'}));
if(content.length == 0) {
return false;
}
return true;
}
Updated: format as text, to get text content from editor. check fiddle
-- Originally wrote it in PHP --
function validation_form()
{
var content = $.trim(tinyMCE.get('main-ment').getContent());
if(content.length == 0) {
return false;
}
return true;
}
Is Correct @A.T
You can use javascript's trim
method.
function validation_form()
{
var content = tinyMCE.get('main-ment').getContent().replace(' ','').trim();
if(content == "" || content == null || content == '<p> </p>') {
return false;
}
}
For more information, please check here
Solution for the same while using Angular Reactive Form Validation
Give this custom validator function in typescript file
emptyLinesValiadtor(control:FormControl):{[s:string]:boolean} | null {
let content = control.value.replaceAll(/ /gm,'')
.trim().split(" ").join("").replaceAll('<p></p>','').trim();
if(content == "" || content == null) {
return {'emptyLines': true}
}
return null;
}
In your Reactive form builder/declaration
this.formName= this.formBuilder.group({
textArea:['',this.emptyLinesValiadtor]
});
In your template form
<div
*ngIf="sForm.submitted && f.textArea.errors">
<div *ngIf="f.textArea.errors.emptyLines">
<div>Answer cannot contain empty lines/spaces</div>
</div>
</div>
where sform is reference variable and f is a typescript get method like below
get f() {
return this.formName.controls;
}