[Django]バリデーションの種類

### CharFieldのバリデーション
– required
– min_length, max_length
– empty_value

class CheckForm(forms.Form):
	empty = forms.CharField(label='Empty', empty_value=True, widget=forms.TextInput(attrs={'class':'form-control'}))
	min = forms.CharField(label='Min', min_length=10, widget=forms.TextInput(attrs={'class':'form-control'}))	
	max = forms.CharField(label='Max', max_length=10, widget=forms.TextInput(attrs={'class':'form-control'}))

### IntegerField/FloatFieldのバリデーション
– required
– min_value, max_value

class CheckForm(forms.Form):
	required = forms.IntegerField(label='Required', widget=forms.NumberInput(attrs={'class':'form-control'}))
	min = forms.IntegerField(label='Min', min_value=100, widget=forms.NumberInput(attrs={'class':'form-control'}))	
	max = forms.IntegerField(label='Max', max_value=1000, widget=forms.NumberInput(attrs={'class':'form-control'}))

### 日時関連のバリデーション
– DateField, TimeField, DateTimeFieldでは日時の各値を表す記号を組み合わせて作成する
– %y, %m, %d, %H, %M, %S

class CheckForm(forms.Form):
	date = forms.DateField(label='Date', input_formats=['%d'], widget=forms.DateInput(attrs={'class':'form-control'}))
	time = forms.TimeField(label='Time', widget=forms.TimeInput(attrs={'class':'form-control'}))
	datetime = forms.DateTimeField(label='DateTime', widget=forms.DateTimeInput(attrs={'class':'form-control'}))

### バリデーションを追加
– Formクラスにメソッドを追加する
– raise ValidationError(“Error message”)
/hello/forms.py

from django import forms

class CheckForm(forms.Form):
	str = forms.CharField(label='String', widget=forms.TextInput(attrs={'class':'form-control'}))

	def clean(self):
		cleaned_data = super().clean()
		str = cleaned_data['str']
		if(str.lower().startswith('no')):
			raise forms.ValidationError('Your input "No!"')